package com.samehope.ar.controller;


import com.alibaba.fastjson.JSON;
import com.samehope.ar.common.CommonResult;
import com.samehope.ar.constant.QrCodeTypeEnum;
import com.samehope.ar.dto.*;
import com.samehope.ar.entity.SysUser;
import com.samehope.ar.service.ISysUserService;
import com.samehope.ar.util.QRCodeUtils;
import com.samehope.ar.util.RedisUtil;
import com.samehope.ar.util.SmsUtils;
import com.samehope.ar.vo.UserCompanyDataVO;
import com.tencentyun.TLSSigAPIv2;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户 前端控制器
 * </p>
 *
 * @author Zhang Luo
 * @since 2019-12-23
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class SysUserController {

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Value("${tencent.sms.templateRegisterID}")
    private String templateRegisterID;

    @Autowired
    private ISysUserService userService;

    /**
     * 返回二维码
     */
    @GetMapping("/qrCode")
    public void qrCode(HttpServletRequest request, HttpServletResponse response) {
        try (ServletOutputStream outputStream = response.getOutputStream()){
            BufferedImage image = QRCodeUtils.createImage(JSON.toJSONString(refreshToken(request)),
                    null, true);
            ImageIO.write(image, "png", outputStream);
            response.setContentType("image/png");
            response.flushBuffer();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 登录逻辑
     * @param param
     * @return
     */
    @PostMapping("/login")
    public CommonResult login(@RequestBody @Valid UserLoginParam param) {
        UserCompanyDataVO userCompanyDataVO = userService.login(param.getMobile(), param.getPassword());
        if (userCompanyDataVO == null) {
            return CommonResult.validateFailed("用户名或密码错误");
        }
        return CommonResult.success(userCompanyDataVO);
    }

    /**
     * 用户刷新TOKEN请求接口 不开放
     * @param request
     * @return
     */
//    @GetMapping(value = "/token/refresh")
    public CommonResult refreshToken(HttpServletRequest request) {
        String token = request.getHeader(tokenHeader);
        String refreshToken = userService.refreshToken(token);
        if (refreshToken == null) {
            return CommonResult.failed();
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", refreshToken);
        tokenMap.put("tokenHead", tokenHead);
        tokenMap.put("type", QrCodeTypeEnum.LOGIN.getCode().toString());
        return CommonResult.success(tokenMap);
    }

    /**
     * 用户登出接口
     * @return
     */
    @PostMapping("/logout")
    public CommonResult logout() {
        return CommonResult.success(null);
    }

    /**
     * 用户注册
     * @return
     */
    @PostMapping("/register")
    public CommonResult register(@RequestBody @Valid UserRegisterParam param) {
        userService.register(param);
        UserLoginParam userLoginParam = new UserLoginParam();
        userLoginParam.setMobile(param.getMobile());
        userLoginParam.setPassword(param.getPassword());
        return this.login(userLoginParam);
    }

    /**
     * 获取验证码
     * @return
     */
    @GetMapping("/sendCode")
    public CommonResult sendCode(@Valid SendCodeParam param) {
        SysUser user = userService.getByMobile(param.getMobile());

        if ((user == null || user.getStatus() == 0) && param.getType() == 2) {
            throw new IllegalArgumentException("该手机号未注册");
        }

        if (user != null && user.getStatus() == 1 && param.getType() == 1) {
            throw new IllegalArgumentException("该手机号码已被注册");
        }

        String code = RedisUtil.get(param.getMobile());
        if (code == null) {
            code = RandomStringUtils.randomNumeric(6);
        }
        RedisUtil.set(param.getMobile(), code, 60L * 5);

        //发送短信
        String[] templateParams={code};
        String[] phoneNumbers={"+86" + param.getMobile()};
        SmsUtils.sendSms(templateRegisterID,templateParams,phoneNumbers);

        log.info("手机号: {}, 验证码: {}", param.getMobile(), code);
        return CommonResult.success(null);
    }

    /**
     * 找回密码
     */
    @PutMapping("/findPassword")
    public CommonResult findPassword(@Valid @RequestBody FindPasswordParam param) {
        userService.findPassword(param);
        return CommonResult.success(null);
    }

    /**
     * 修改密码
     * @return
     */
    @PutMapping("/modifyPassword")
    public CommonResult modifyPassword(@Valid @RequestBody ModifyPasswordParam param) {
        userService.modifyPassword(param);
        return CommonResult.success(null);
    }

    /**
     * 修改个人资料
     * @param param
     * @return
     */
    @PutMapping("/updateUserInfo")
    public CommonResult updateUserInfo(@Valid @RequestBody UpdateUserInfoParam param) {
        userService.updateUserInfo(param);
        return CommonResult.success(null);
    }

    /**
     * 获取个人资料
     * @return
     */
    @GetMapping("/getUserInfo")
    public CommonResult getUserInfo() {
        return CommonResult.success(userService.getUserInfo());
    }

    /**
     * 实时音视频获取用户sig
     * @return
     */
    @GetMapping("/getUserSig")
    public CommonResult getUserSig(String userId) {
        TLSSigAPIv2 tlsSigAPIv2 = new TLSSigAPIv2(1400300177, "199cd4689b1621a6346eaabb7480e2e7a88970f48c314b8f953192e15d0b85d2");
        String userSig = tlsSigAPIv2.genSig(userId, 180 * 86400);
        return CommonResult.success(userSig);
    }
}
